import { NameSpace } from 'utils/index';
import { Message } from '@teamix/ui';

import exceed from 'utils/apimap';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;

const ns = NameSpace('webhooks');
export const RECEIVE_WEBHOOKS = ns('RECEIVE_WEBHOOKS');
export const CREATE_WEBHOOK = ns('CREATE_WEBHOOK');
export const REMOVE_WEBHOOK = ns('REMOVE_WEBHOOK');
export const TEST_RESULT = ns('TEST_RESULT');
export const UPDATE_DATA = ns('UPDATE_DATA');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// 查询webhooks列表
export function getWebhooks() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'project.web_hooks',
        params: {
          projectId: pathResource.id,
        },

        data: {
          per_page: 100,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_WEBHOOKS,
          data: result.list.sort((a, b) => a.type - b.type),
        });
      });
  };
}

// 新建webhook
export function create(formData, cb) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'project.web_hooks.add',
        params: {
          projectId: pathResource.id,
        },

        data: formData,
      })
      .then((result) => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsWebhooks.actions.WebhookCreated',
              defaultMessage: 'Webhook 新建成功',
            }),
          });
        }, 500);
        dispatch({
          type: CREATE_WEBHOOK,
          data: result,
        });

        cb && cb();
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };
}

// 测试webhook
export function testHook(hookId, cb) {
  return (dispatch, getState) => {
    const state = getState().project.projectSettings.settingsWebhooks;
    const { webhooks } = state;
    const hookTestResult = webhooks.find((item) => item.id === hookId);

    exceed
      .fetch({
        api: 'project.web_hooks.test',
        params: {
          projectId: pathResource.id,
          webhookId: hookId,
        },
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.settingsWebhooks.actions.WebhookTestSucceeded',
            defaultMessage: 'Webhook 测试成功',
          }),
          duration: 2000,
        });

        hookTestResult.last_test_result = 'ok';
        dispatch({
          type: TEST_RESULT,
          data: [...webhooks],
        });

        cb && cb();
      })
      .fail(() => {
        hookTestResult.last_test_result = 'error';
        dispatch({
          type: TEST_RESULT,
          data: [...webhooks],
        });

        cb && cb();
      });
  };
}

// 删除webhook
export function remove(hookId, cb) {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'project.web_hooks.delete',
        params: {
          projectId: pathResource.id,
          webhookId: hookId,
        },
      })
      .then(() => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsWebhooks.actions.WebhookDeleted',
              defaultMessage: 'Webhook 删除成功',
            }),
          });
        }, 500);
        dispatch({
          type: REMOVE_WEBHOOK,
          data: hookId,
        });

        cb && cb();
      });
  };
}

// 查询某一条webhook
export function getOneHook(hookId, cb) {
  return () => {
    exceed
      .forceFetch({
        api: 'project.web_hooks.get',
        params: {
          projectId: pathResource.id,
          webhookId: hookId,
        },
      })
      .then((result) => {
        cb(result);
      });
  };
}

// 编辑webhook
export function edit(hookId, formData, cb) {
  return (dispatch, getState) => {
    const state = getState().project.projectSettings.settingsWebhooks;
    const { webhooks } = state;

    exceed
      .fetch({
        api: 'project.web_hooks.edit',
        params: {
          projectId: pathResource.id,
          webhookId: hookId,
        },

        data: formData,
      })
      .then((result) => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsWebhooks.actions.WebhookUpdated',
              defaultMessage: 'Webhook 更新成功',
            }),
          });
        }, 500);
        const hook = webhooks.map((element) => {
          if (element.id === hookId) {
            element = result;
          }
          return element;
        });
        dispatch({
          type: RECEIVE_WEBHOOKS,
          data: hook,
        });

        cb && cb();
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };
}
